'''
导入 json 库：import json
json文件的操作方法：
json.load()：从 json 文件 读取数据，转为 python 的数据类型（重点掌握
json.loads()：从 json 串 读取数据，转为 python 的数据类型
json.dump():把 python 的数据类型转为 json 串，存放到 文件 中（重点掌握
json.dumps():把 python 的数据类型转为 json 串，存放到 字符串 中
'''
import json

# 案例1：load()
with open(r'username.json', mode='r', encoding='utf-8') as f:
    data = json.load(f)
    print(data)
    print(type(data))

# json串的两种表现方式：
json_str1 = '{"id": 1, "name": "TOM", "age": 18}'
json_str2 = '[{"id": 1, "name": "TOM", "age": 18},{"id": 2, "name": "MARY", "age": 18},{"id": 3, "name": "AMY", "age": 18}]'
print(type(json_str2))

# 案例2：loads()
data = json.loads(json_str2)
print(data)
print(type(data))

# 案例3：dump()
stu_list = [{"id": 1, "name": "TOM", "age": 18}, {"id": 2, "name": "MARY", "age": 18},
            {"id": 3, "name": "AMY", "age": 18}]
with open(r'username2.json', mode='w', encoding='utf-8') as f:
    json.dump(stu_list, f, ensure_ascii=False)  # ensure_ascii 禁止ascii转换

# 案例4：dumps()
stu_list = [{"id": 1, "name": "TOM", "age": 18}, {"id": 2, "name": "MARY", "age": 18},
            {"id": 3, "name": "AMY", "age": 18}]
stu_json_str = json.dumps(stu_list)
print(stu_json_str)
print(type(stu_json_str))

